package com.dllo.lanou.cookapp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.ToxicBakery.viewpager.transforms.ABaseTransformer;
import com.ToxicBakery.viewpager.transforms.CubeOutTransformer;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.dllo.lanou.cookapp.BaseApplication;
import com.dllo.lanou.cookapp.R;
import com.dllo.lanou.cookapp.activity.DetatViewPagerActivity;
import com.dllo.lanou.cookapp.activity.SearchActivity;
import com.dllo.lanou.cookapp.adapter.HomeListFoodAdapter;
import com.dllo.lanou.cookapp.entity.HeadViewPageEntity;
import com.dllo.lanou.cookapp.entity.HeadViewPageResultEntity;
import com.dllo.lanou.cookapp.entity.User;
import com.dllo.lanou.cookapp.utils.NetworkImageHolderView;
import com.dllo.lanou.cookapp.volly.VolleySingleton;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;

/**
 * Created by xijinhua on 2016/2/12.
 */
public class HomePagerFragment extends Fragment implements OnItemClickListener, View.OnClickListener {
    //@Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    private List<String> imgs;
    private List<HeadViewPageResultEntity> resultEntities= new ArrayList<>();//listview
    private List<HeadViewPageResultEntity> resultEntities1 = new ArrayList<>();//viewpager
    @Bind(R.id.home_list)
    ListView homelist;
    private HomeListFoodAdapter adapter;
    private View headerView;
    private LinearLayout  search;



    @Nullable
    @Override
    //初始化布局
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_homepage, container, false);
        headerView = getLayoutInflater(savedInstanceState).inflate(R.layout.listview_header, null);
        ButterKnife.bind(this,view);
        convenientBanner = (ConvenientBanner) headerView.findViewById(R.id.convenientBanner);
        search = (LinearLayout) headerView.findViewById(R.id.search);
        adapter = new HomeListFoodAdapter(getActivity());
        homelist.addHeaderView(headerView, null, true);
        return view ;
    }

    @Override
    //初始化控件
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
      //  headerView = getLayoutInflater(savedInstanceState).inflate(R.layout.listview_header, null);
      //  convenientBanner = (ConvenientBanner) headerView.findViewById(R.id.convenientBanner);
       // homelist = (ListView) view.findViewById(R.id.home_list);
       // search = (LinearLayout) headerView.findViewById(R.id.search);
      //  adapter = new HomeListFoodAdapter(getActivity());

       // Log.i("测试2", BmobUser.getCurrentUser(getActivity(), User.class)+"");
       // homelist.addHeaderView(headerView, null, true);
        search.setOnClickListener(this);
        convenientBanner.setOnItemClickListener(this);
        // initImageLoader();
    }

    //数值操作
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String transforemerName = CubeOutTransformer.class.getSimpleName();
        try {
            Class cls = Class.forName("com.ToxicBakery.viewpager.transforms." + transforemerName);
            ABaseTransformer transforemer = null;
            try {
                transforemer = (ABaseTransformer) cls.newInstance();
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            }
            convenientBanner.getViewPager().setPageTransformer(true, transforemer);

            //部分3D特效需要调整滑动速度
            if (transforemerName.equals("StackTransformer")) {
                convenientBanner.setScrollDuration(1200);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        String httpArg = "id=8&rows=5";
        String httpArg2 = "id=14&page=2&rows=20";
        requestData(httpArg);//viewpager的请求数据
        requestData(httpArg2);

        homelist.setAdapter(adapter);
        homelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                long list_id = resultEntities.get(position-1).getId();
                Toast.makeText(getActivity(), "" + list_id, Toast.LENGTH_LONG).show();
                Intent intent = new Intent(getActivity(), DetatViewPagerActivity.class);
                intent.putExtra("id", list_id);
                startActivity(intent);
            }
        });

    }


    //请求数据
    public void requestData(final String httpArg) {
        String path = "http://apis.baidu.com/tngou/cook/list";
        //  String httpArg = "id=1&page=1&rows=5";
        String url = path + "?" + httpArg;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                HeadViewPageEntity entity = gson.fromJson(response, HeadViewPageEntity.class);
                if (entity != null) {


                    if ("id=8&rows=5".equals(httpArg)) {
                        resultEntities1 = entity.getTngou();
                        imgs = new ArrayList<>();
                        String pa = "http://tnfs.tngou.net/img";
                        imgs.add(pa + resultEntities1.get(0).getImg());
                        imgs.add(pa + resultEntities1.get(1).getImg());
                        imgs.add(pa + resultEntities1.get(2).getImg());
                        imgs.add(pa + resultEntities1.get(3).getImg());
                        imgs.add(pa + resultEntities1.get(4).getImg());
                        System.out.println("第一条信息:" + imgs);
                        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                            @Override
                            public NetworkImageHolderView createHolder() {
                                return new NetworkImageHolderView();
                            }
                        }, imgs);
                    } else if ("id=14&page=2&rows=20".equals(httpArg)) {
                        Log.i("我的请求数据", response);

                        resultEntities = entity.getTngou();
                        adapter.addData(resultEntities);
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            //在StringRespset结束之前写{}在大括号里面写 getHeaders() 自动重写方法
            //用Map方法键值对形势添加
            //添加请求头
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("apikey", "4ee0087cd4103e3acbab0f8efbf0bbd1");
                return map;
            }


        };
        VolleySingleton.getInstance().addRequest(request);
    }


    //初始化网络图片缓存库
  /*  private void initImageLoader(){
        //网络图片例子,结合常用的图片缓存库UIL,你可以根据自己需求自己换其他网络图片库
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
                showImageForEmptyUri(R.drawable.ic_default_adimage)
                .cacheInMemory(true).cacheOnDisk(true).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getContext()).defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }?*/

    @Override
    public void onResume() {
        super.onResume();


        convenientBanner.startTurning(5000);
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
       convenientBanner.stopTurning();
    }

    @Override
    public void onItemClick(int i) {

        long id = resultEntities1.get(i).getId();
        Toast.makeText(getActivity(), "" + id, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getActivity(), DetatViewPagerActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);

    }

    @Override
    public void onClick(View v) {
            switch (v.getId()){
                case R.id.search:
                    Intent intent = new Intent(getActivity(),SearchActivity.class);
                    intent.putExtra("search",true);
                    startActivity(intent);
                    break;
            }
    }
}
